package com.qiguliuxing.dts.admin.web;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.admin.dao.InstrumentAll;
import com.qiguliuxing.dts.admin.dao.ProductProductionAll;
import com.qiguliuxing.dts.admin.dao.ProductsTemplate;
import com.qiguliuxing.dts.admin.dao.dto.ProductPageQuery;
import com.qiguliuxing.dts.admin.service.AdminIorderService;
import com.qiguliuxing.dts.admin.service.AdminProductProductionService;
import com.qiguliuxing.dts.admin.util.AuthSupport;
import com.qiguliuxing.dts.core.util.ResponseUtil;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.GmInstrument;
import com.qiguliuxing.dts.db.domain.IoralRaw;
import com.qiguliuxing.dts.db.domain.ProductProduction;
import com.qiguliuxing.dts.db.service.IoralRawService;
import com.qiguliuxing.dts.db.service.ProductProductionService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/productProduction")
@Validated
public class AdminProductProductionController {

    @Autowired
    private AdminProductProductionService adminProductProductionService;
    @Autowired
    private ProductProductionService productProductionService;
    @Autowired
    private IoralRawService ioralRawService;
    private static final Logger logger = LoggerFactory.getLogger(AdminProductProductionController.class);

    @RequiresPermissions("admin:productProduction:list")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "查询")
    @PostMapping("/list")
    public Object list(@RequestBody ProductPageQuery productPageQuery/*@RequestParam(defaultValue = "2024-01-01") String startTime, @RequestParam(defaultValue = "2024-12-01")String endTime,@RequestParam(value="batchNumber") String batchNumber, @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "20") Integer limit,
                       @RequestParam(defaultValue = "measure_tine") String sort,
                       @RequestParam(defaultValue = "desc") String order*/) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", productPageQuery.toString());
        if(productPageQuery.getIsNew()!=0) {
            String startTime = "";
            String endTime = "";
            List<String> ste = new ArrayList<>();
            ste = productPageQuery.getStartToEnd();
            if (ste != null && !ste.isEmpty()) {
                startTime = ste.get(0).substring(0, 10);
                endTime = ste.get(1).substring(0, 10);
                logger.info(ste.toString());
                logger.info(startTime + endTime);
            }
            return adminProductProductionService.list(startTime,endTime,productPageQuery.getBatchNumber(),productPageQuery.getPage(), productPageQuery.getLimit(),productPageQuery.getSort(),productPageQuery.getOrder());
        }else{
            List<ProductProduction> productProductions=productProductionService.queryNew(productPageQuery.getPage(), productPageQuery.getLimit(),productPageQuery.getSort(),productPageQuery.getOrder());
            long total = PageInfo.of(productProductions).getTotal();
            Map<String, Object> data = new HashMap<>();
            data.put("total", total);
            data.put("items", productProductions);
            logger.info("【请求结束】碘订单管理->仪器列表->查询,响应结果:{}", JSONObject.toJSONString(data));

            return ResponseUtil.ok(data);
        }


        }


    @GetMapping("/listByOrder")
    public Object list2(@RequestParam(defaultValue = "2024-01-01") String startTime, @RequestParam(defaultValue = "2024-12-01")String endTime,@RequestParam(value="batchNumber") String batchNumber, @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "20") Integer limit,
                       @RequestParam(defaultValue = "measure_tine") String sort,
                       @RequestParam(defaultValue = "desc") String order) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", page);
          logger.info(sort+order);


        return adminProductProductionService.list(startTime,endTime,batchNumber,page, limit, sort,order);
    }


    /*@RequiresPermissions("admin:productProduction:list")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "查询")
    @GetMapping("/list")
    public Object list22(@RequestParam(defaultValue = "2024-01-01") String startTime, @RequestParam(defaultValue = "2024-12-01")String endTime,@RequestParam(value="batchNumber") String batchNumber, @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "20") Integer limit,@RequestParam(defaultValue = "0") Integer isNew*//*,
                       @Sort @RequestParam(defaultValue = "id") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order*//*) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", page);
        //需要区分数据权限，如果属于品牌商管理员，则需要获取当前用户管理品牌店铺
        *//*   List<Integer> brandIds = null;*//**//*
         *//**//*if (adminDataAuthService.isBrandManager()) {*//**//*
         *//**//*        brandIds = adminDataAuthService.getBrandIds();
            logger.info("运营商管理角色操作，需控制数据权限，brandIds:{}",JSONObject.toJSONString(brandIds));

            if (brandIds == null || brandIds.size() == 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0L);
                data.put("items", null);

                logger.info("【请求结束】商品管理->商品管理->查询,响应结果:{}", JSONObject.toJSONString(data));
                return ResponseUtil.ok(data);
          *//**//**//**//*  }*//**//*
         *//**//*     }*//*


        return adminProductProductionService.list(startTime,endTime,batchNumber,page, limit,isNew*//*, sort,order*//*);
    }*/




    @GetMapping("/getInfoByOrderCounts")
    public Object getInfoByOrderCount(@RequestParam(value="batchNumber") String batchNumber,@RequestParam(value="orderCount") String orderCount,@RequestParam(value="useTime") String useTime,@RequestParam(value="piece") Integer piece) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->查询,请求参数:instrumentNumber:{},instrumentName:{},page:{}", orderCount);
        //需要区分数据权限，如果属于品牌商管理员，则需要获取当前用户管理品牌店铺
        logger.info(useTime);
        /*   List<Integer> brandIds = null;*//*
         *//*if (adminDataAuthService.isBrandManager()) {*//*
         *//*        brandIds = adminDataAuthService.getBrandIds();
            logger.info("运营商管理角色操作，需控制数据权限，brandIds:{}",JSONObject.toJSONString(brandIds));

            if (brandIds == null || brandIds.size() == 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("total", 0L);
                data.put("items", null);

                logger.info("【请求结束】商品管理->商品管理->查询,响应结果:{}", JSONObject.toJSONString(data));
                return ResponseUtil.ok(data);
          *//**//*  }*//*
         *//*     }*/


        return adminProductProductionService.getOrderInfo(batchNumber,orderCount,useTime,piece/*, sort,order*/);
    }

/*    @GetMapping("/catAndBrand")
    public Object catAndBrand() {
        return adminInstrumentService.catAndBrand();
    }*/

    /**
     * 编辑商品
     *
     * @param productProductionAll
     * @return
     */
    @RequiresPermissions("admin:productProduction:update")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody ProductProductionAll productProductionAll) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->生产列表->编辑,请求参数:{}", JSONObject.toJSONString(productProductionAll));

        return adminProductProductionService.update(productProductionAll);
    }

    @RequiresPermissions("admin:productProduction:insertMany")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "导入")
    @GetMapping("/insertMany")
    public boolean addUser(@RequestParam("file") MultipartFile file) {
        boolean a = false;
        String fileName = file.getOriginalFilename();
        try {
            /* a = itestService.batchImport(fileName, file);*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  a;
    }

    /**
     * 删除器材
     *
     * @param productProduction
     * @return
     */
 /*   @RequiresPermissions("admin:productProduction:deleteProductProduction")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody ProductProduction productProduction) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘131生产发货管理->删除,请求参数:{}", JSONObject.toJSONString(productProduction));

        return adminProductProductionService.delete(productProduction);
    }
*/
    /*@RequiresPermissions("admin:instrument:insertMany")
    public Object insertMany(@RequestBody List<InstrumentAll> list){

        return
    }
*/
    /**
     * 添加商品
     *哈哈哈哈哈哈哈哈哈

     * @return
     */
    @RequiresPermissions("admin:productProduction:create")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "添加")
    @GetMapping("/create")
    public Object create(@RequestParam(value = "batchNumber")String batchNumber,
                         Integer rawConcentration,
                         String rawNumber1,
                         String rawNumber2,
                         Integer oralConcentration,
                         @RequestParam(value = "sampleRetention")Double sampleRetention,
                         @RequestParam(value = "productionDate")String productionDate,
                         Double productionCapacity,
                         @RequestParam(value = "measureTime")String measureTime,
                         Double productionActivity) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName() + "] 碘131生产发货管理->订单列表->新增,请求参数:{}", JSONObject.toJSONString(productProductionService));
        DecimalFormat decimalFormat = new DecimalFormat("#0.00");
        ProductProduction productProduction = new ProductProduction();
        productProduction.setBatchNumber(batchNumber);
        if(productionDate!=null){
            String s=productionDate.substring(0,10);
            productProduction.setProductionDate(LocalDate.parse(s));
        }
        if(measureTime!=null){
            productProduction.setMeasureTine(LocalDateTime.parse(measureTime));
        }
        productProduction.setSampleRetention(sampleRetention);


        productProduction.setProductActivity(productionActivity);
        productProduction.setProductCapacity(productionCapacity);
        productProduction.setRemainingActivity(productionActivity-sampleRetention*oralConcentration/1000);
        productProduction.setRemainingCapacity(productionCapacity-sampleRetention);
       productProduction.setOralConcentration(oralConcentration);
       productProduction.setRawNumber1(rawNumber1);
       productProduction.setRawNumber2(rawNumber2);
       List<IoralRaw> ioralRaws=ioralRawService.queryByNew(1,30);
        if(rawNumber1!=null && rawNumber1.length()>0){
             for(IoralRaw ioralRaw:ioralRaws){

                 if(ioralRaw.getBatchNumber()==rawNumber1){
                    productProduction.setRawNumber1(ioralRaw.getBatchNumber());
                     ioralRaw.setRemainingActivity(ioralRaw.getRemainingActivity()-productionActivity);
                 }
             }

       }
        if(rawNumber2!=null && rawNumber2.length()>0){
            for(IoralRaw ioralRaw:ioralRaws){

                if(ioralRaw.getBatchNumber()==rawNumber2){
                    productProduction.setRawNumber2(ioralRaw.getBatchNumber());
                    ioralRaw.setRemainingActivity(ioralRaw.getRemainingActivity()-productionActivity);
                }
            }

        }
       productProduction.setRawConcentration(rawConcentration);

        logger.info(productProduction.toString());
        return adminProductProductionService.create(productProduction);
    }

    /**
     * 器材详情
     *
     * @param id
     * @return
     */
    @RequiresPermissions("admin:productProduction:read")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "详情")
    @GetMapping("/detail")
    public Object detail(@NotNull Integer id) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘生产管理->详情,请求参数,id:{}", id);
        logger.info("hehehehheheh");
        return adminProductProductionService.detail(id);
    }


 /*   @GetMapping("/setEnd")
    public Object setEnd(@RequestBody List<Product> id) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘生产管理->详情,请求参数,id:{}", id);
        logger.info("hehehehheheh");
        return adminProductProductionService.detail(id);
    }
*/

    @RequiresPermissions("admin:productProduction:read")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "查看产品信息")
    @GetMapping("/info")
    public Object detail(@NotNull String batchNumber) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘生产管理->详情,请求参数,id:{}", batchNumber);
        logger.info("根据产品信息查找产品");
        return adminProductProductionService.detail(batchNumber);
    }

    /*@RequiresPermissions("admin:productProduction:read")*/
    /*@RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, buttond = "查看产品信息")*/
    @PostMapping("/queryBatchNumbers")
    public Object getBatchNumbers(@RequestBody ProductPageQuery productPageQuery) {
        String startTime = "";
        String endTime = "";
        if(productPageQuery.getIsNew()!=0) {

            List<String> ste = new ArrayList<>();
            ste = productPageQuery.getStartToEnd();
            if (ste != null && !ste.isEmpty()) {
                startTime = ste.get(0).substring(0, 10);
                endTime = ste.get(1).substring(0, 10);
                logger.info(ste.toString());
                logger.info(startTime + endTime);
            }
        }
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘生产管理->详情,请求参数,id:{}");
        logger.info("查找所有产品批号");
        Map<String,Object> data=new HashMap<>();
        Map<String,String> batchNumbers2=new TreeMap<>();
        Object batchNumbers=null;
        List<ProductProduction> productProductions=productProductionService.querySelective2(startTime,endTime,"production_date","asc");
        List<LocalDate> batchNumbers3=new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for(ProductProduction production:productProductions){
            if(production.getIsEnd()==Boolean.FALSE) {
                String bn = production.getBatchNumber();
                batchNumbers3.add(LocalDate.parse(production.getBatchNumber()));
                /*batchNumbers2.put(bn,dateFormat.format(Date.valueOf(bn)));*/
            }else{
                productProductions.remove(production);
            }
        }
        batchNumbers3.sort((d1, d2) -> d2.compareTo(d1));


       /* batchNumbers2.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())*/


               /* .forEach(entry ->
                        *//*System.out.println(dateFormat.format(entry.getKey()) + ": " + entry.getValue())*//*
                )*/;
       /* batchNumbers=batchNumbers2.stream()
                .collect(Collectors.groupingBy(s -> s.substring(0, 10)))
                .entrySet()
                .stream()
                .map(entry -> {
                    Map<String, Object> group = Map.of(
                            "label", entry.getKey().substring(0,10),
                            "options", entry.getValue()*//*.stream().map(option -> Map.of("value", option, "label", option)).collect(Collectors.toList())*//*
                    );
                    return group;
                })
                .collect(Collectors.toList());*/
        data.put("batchNumbers",batchNumbers3);
        /*logger.info(batchNumbers.toString());*/
        return ResponseUtil.ok(data);
    }

    @PostMapping("/queryBatchNumbers2")
    public Object getBatchNumbers2(@RequestBody ProductPageQuery productPageQuery) {
        String startTime="";
        String endTime="";
        List<String> ste=new ArrayList<>();
        ste=productPageQuery.getStartToEnd();
        if(ste!=null && !ste.isEmpty()) {
            startTime = ste.get(0).substring(0, 10);
            endTime = ste.get(1).substring(0, 10);
            logger.info(ste.toString());
            logger.info(startTime + endTime);
        }
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘生产管理->详情,请求参数,id:{}", startTime+endTime);
        logger.info("查找所有产品批号");
        Map<String,Object> data=new HashMap<>();
        Map<String,String> batchNumbers2=new TreeMap<>();
        LinkedHashMap<String,LocalDate> batchNumbers6=new LinkedHashMap<>();
        Object batchNumbers=null;
        List<ProductProduction> productProductions=productProductionService.querySelective2(startTime,endTime,"production_date","asc");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<LocalDate> batchNumbers4=new ArrayList<>();
        for(ProductProduction production:productProductions){

                String bn = production.getBatchNumber();
                batchNumbers2.put(bn,bn/*dateFormat.format(Date.valueOf(bn))*/);
            batchNumbers4.add(LocalDate.parse(production.getBatchNumber()));

        }
        batchNumbers4.sort((d1, d2) -> d2.compareTo(d1));


        for(LocalDate sss : batchNumbers4){
            batchNumbers6.put(sss.toString(),sss);
        }
        /*batchNumbers2.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())*/

        /* .forEach(entry ->
         *//*System.out.println(dateFormat.format(entry.getKey()) + ": " + entry.getValue())*//*
                )*/;
       /* batchNumbers=batchNumbers2.stream()
                .collect(Collectors.groupingBy(s -> s.substring(0, 10)))
                .entrySet()
                .stream()
                .map(entry -> {
                    Map<String, Object> group = Map.of(
                            "label", entry.getKey().substring(0,10),
                            "options", entry.getValue()*//*.stream().map(option -> Map.of("value", option, "label", option)).collect(Collectors.toList())*//*
                    );
                    return group;
                })
                .collect(Collectors.toList());*/
        data.put("batchNumbers",batchNumbers6);
        /*logger.info(batchNumbers.toString());*/
        return ResponseUtil.ok(data);
    }
    @PostMapping("/setEnd")
    public Object setEnd(@RequestBody List<ProductsTemplate> productsTemplates){

        if(productsTemplates!=null){
            for(ProductsTemplate productsTemplate:productsTemplates){
                String batchNumber=productsTemplate.getBatchNumber();
                Integer id=productsTemplate.getId();
                ProductProduction production=productProductionService.findById(id);
                production.setIsEnd(true);
                productProductionService.updateById(production);
                productsTemplate.setIsEnd("true");
            }
            Map<String,Object> data=new HashMap<>();
            data.put("total",productsTemplates.size());
            return ResponseUtil.ok(data);
        }else{
            return null;
        }


    }


    @RequiresPermissions("admin:productProduction:read")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "详情")
    @GetMapping("/more")
    public Object detail2(@NotNull Integer id) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘生详情,请求参数,id:{}", id);
        logger.info("heheh胜多负少h");
        return adminProductProductionService.detail(id);
    }
    /**
     * 删除生产信息
     *
     * @param productProduction
     * @return
     */
    @RequiresPermissions("admin:productProduction:deleteProductProduction")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "删除")
    @PostMapping("/deleteProductProduction")
    public Object delete(@RequestBody ProductProduction productProduction) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 器材管理->器材管理->删除,请求参数:{}", JSONObject.toJSONString(productProduction));

        return adminProductProductionService.delete(productProduction);
    }

/*    @RequiresPermissions("admin:productProduction:read")
    @RequiresPermissionsDesc(menu = { "碘131生产发货管理", "生产列表" }, button = "详情")
    @GetMapping("/more")
    public Object detail2(@NotNull Integer id) {
        logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 碘生详情,请求参数,id:{}", id);
        logger.info("heheh胜多负少h");
        return adminProductProductionService.detail(id);
    }*/


}
